# encoding: utf-8
# @File  : test01.py
# @Author: wu shaofan
# @Desc : 调试seleium驱动谷歌浏览器
# @Date  :  2024/02/07
import os
import time

import cv2
import requests
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
import conftest
from selenium.webdriver.support import expected_conditions as EC
# 1.初始化
page_url = 'https://dun.163.com/trial/jigsaw'
# 滑块按钮class
btn_class = '.yidun_slider.yidun_slider--hover'
# 背景图class
bg_img_class = '.yidun_bg-img'
# 滑块图class
sl_img_class = '.yidun_jigsaw'

#  背景图本地保存路径
bg_img_path = 'background.png'
# 滑块图本地保存路径
sl_img_path = 'slider.png'

def get_and_save_img(xpath, fpath):
    img_url = wait.until( lambda x: x.find_element(By.CSS_SELECTOR,xpath) ).get_attribute('src')
    # 判断文件夹是否存在不存在则创建'
    os.makedirs('./image/', exist_ok=True)
    with open('./image/'+fpath, 'wb') as f:
        resp = requests.get(img_url)
        f.write(resp.content)

# 设置 Chrome WebDriver 路径
chrome_driver_path = conftest.BASE_DIR + '/tool/chromedriver.exe'
# 创建 ChromeOptions 对象
options = Options()
options.add_experimental_option("excludeSwitches", ["enable-logging"])
# 创建 Chrome WebDriver 服务
service = Service(chrome_driver_path)
# 创建 Chrome WebDriver 实例
driver = webdriver.Chrome(service=service, options=options)
# 窗口最大化
driver.maximize_window()
# 打开网址
driver.get(page_url)

# 滚动页面滑动条，让滑块显示出来
js = 'document.documentElement.scrollTop=200'
driver.execute_script(js)

# 等待某个条件成立时继续执行，否则在达到最大时长时抛超时异常
wait = WebDriverWait(driver, 10)

# 等待按钮可以被点击
slider_element = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, btn_class)))
# 点击按钮，触发滑块
slider_element.click()

# 获取背景图和滑块图
get_and_save_img(bg_img_class,bg_img_path)
get_and_save_img(sl_img_class,sl_img_path)


def cal_offset(bg_img_path, sl_img_path):
    bg_img_path =  './image/'+bg_img_path
    sl_img_path =  './image/'+sl_img_path
    img_rto = 1  # 0.667
    bg_mat = cv2.imread(bg_img_path, cv2.IMREAD_GRAYSCALE)
    sl_mat = cv2.imread(sl_img_path, cv2.IMREAD_GRAYSCALE)

    bg_w, bg_h = round(bg_mat.shape[1] * img_rto), round(bg_mat.shape[0] * img_rto)
    sl_w, sl_h = round(sl_mat.shape[1] * img_rto), round(sl_mat.shape[0] * img_rto)

    bg_mat = cv2.resize(bg_mat, (bg_w, bg_h))
    sl_mat = cv2.resize(sl_mat, (sl_w, sl_h))

    # 计算X轴滑动距离
    res = cv2.matchTemplate(bg_mat, sl_mat, cv2.TM_CCOEFF_NORMED)
    minVal, maxVal, minLoc, maxLoc = cv2.minMaxLoc(res)

    print(minVal, maxVal, minLoc, maxLoc)

    debug_mat = cv2.cvtColor(bg_mat, cv2.COLOR_GRAY2RGB)
    cv2.rectangle(debug_mat, (maxLoc[0], 1), (maxLoc[0] + sl_w, sl_h - 1), (255, 0, 0))

    cv2.imwrite('debug-match-template.png', debug_mat)
    # plt.matshow(debug_mat)

    return maxLoc[0]

a = cal_offset('background.png', 'slider.png')
print(a)
# 创建行动链
actions = ActionChains(driver)
# 计算x轴滑动距离
offset = a + 10
# 按下滑块并保持
actions.click_and_hold(slider_element)
# 模拟鼠标移动
actions.move_by_offset(offset, 0)
# 释放鼠标
actions.release()
# 执行行动链
actions.perform()


time.sleep(3)
# 退出浏览器
driver.quit()